home *** CD-ROM | disk | FTP | other *** search
/ The 640 MEG Shareware Studio 2 / The 640 Meg Shareware Studio CD-ROM Volume II (Data Express)(1993).ISO / clang / zcpp_jae.zip / CPP6.C < prev    next >
C/C++ Source or Header  |  1990-07-06  |  35KB  |  1,142 lines

  1. /*
  2.  
  3.  
  4.  Copyright (C) 1990 Texas Instruments Incorporated.
  5.  
  6.  Permission is granted to any individual or institution to use, copy, modify,
  7.  and distribute this software, provided that this complete copyright and
  8.  permission notice is maintained, intact, in all copies and supporting
  9.  documentation.
  10.  
  11.  Texas Instruments Incorporated provides this software "as is" without
  12.  express or implied warranty.
  13.  
  14.  
  15.  *                C P P 6 . C
  16.  *        S u p p o r t   R o u t i n e s
  17.  *
  18.  * Edit History
  19.  * 25-May-84 MM        Added 8-bit support to type table.
  20.  * 30-May-84 ARF    sharp() should output filename in quotes
  21.  * 02-Aug-84 MM        Newline and #line hacking.  sharp() now in cpp1.c
  22.  * 31-Aug-84 MM        USENET net.sources release
  23.  * 11-Sep-84 ado/MM    Keepcomments, also line number pathological
  24.  * 12-Sep-84 ado/MM    bug if comment changes to space and we unget later.
  25.  * 03-Oct-84 gkr/MM    Fixed scannumber bug for '.e' (as in struct.element).
  26.  * 04-Oct-84 MM        Added ungetstring() for token concatenation
  27.  * 08-Oct-84 MM        Yet another attack on number scanning
  28.  * 31-Oct-84 ado    Parameterized $ in identifiers
  29.  *  2-Nov-84 MM        Token concatenation is messier than I thought
  30.  *  6-Dec-84 MM        \<nl> is everywhere invisible.
  31.  * 21-Oct-85 RMS    Rename `token' to `tokenbuf'.
  32.  *            Dynamically allocate it, and make it as big as needed.
  33.  * 23-Oct-85 RMS    Fix bugs storing into tokenbuf as it gets bigger.
  34.  *             Change error msg to  cpp: "FILE", line LINE: MSG
  35.  * 24-Oct-85 RMS    Turn off warnings about / * inside a comment.
  36.  * 05-May-89 LGO    When in a macro, change \newline to just newline
  37.  * 19-Jan-90 DKM        Support for MVS and EBCDIC character set
  38.  * 02-May-90 MJF        Backslash<newline> not expanded in scanstring()
  39.  * 02-May-90 MJF        Added macro recursion fixes by Aditya in macroid()
  40.  */
  41.  
  42. #include    <stdio.h>
  43. #include    <ctype.h>
  44. #include    "cppdef.h"
  45. #include    "cpp.h"
  46.  
  47. /*
  48.  * skipnl()    skips over input text to the end of the line.
  49.  * skipws()    skips over "whitespace" (spaces or tabs), but
  50.  *        not skip over the end of the line.  It skips over
  51.  *        TOK_SEP, however (though that shouldn't happen).
  52.  * scanid()    reads the next token (C identifier) into tokenbuf.
  53.  *        The caller has already read the first character of
  54.  *        the identifier.  Unlike macroid(), the token is
  55.  *        never expanded.
  56.  * macroid()    reads the next token (C identifier) into tokenbuf.
  57.  *        If it is a #defined macro, it is expanded, and
  58.  *        macroid() returns TRUE, otherwise, FALSE.
  59.  * scanstring()    Reads a string from the input stream, calling
  60.  *        a user-supplied function for each character.
  61.  *        This function may be output() to write the
  62.  *        string to the output file, or save() to save
  63.  *        the string in the work buffer.
  64.  * scannumber()    Reads a C numeric constant from the input stream,
  65.  *        calling the user-supplied function for each
  66.  *        character.  (output() or save() as noted above.)
  67.  * save()    Save one character in the work[] buffer.
  68.  * savestring()    Saves a string in malloc() memory.
  69.  * getfile()    Initialize a new FILEINFO structure, called when
  70.  *        #include opens a new file, or a macro is to be
  71.  *        expanded.
  72.  * getmem()    Get a specified number of bytes from malloc memory.
  73.  * output()    Write one character to stdout (calling putchar) --
  74.  *        implemented as a function so its address may be
  75.  *        passed to scanstring() and scannumber().
  76.  * lookid()    Scans the next token (identifier) from the input
  77.  *        stream.  Looks for it in the #defined symbol table.
  78.  *        Returns a pointer to the definition, if found, or NULL
  79.  *        if not present.  The identifier is stored in tokenbuf.
  80.  * defnedel()    Define enter/delete subroutine.  Updates the
  81.  *        symbol table.
  82.  * get()    Read the next byte from the current input stream,
  83.  *        handling end of (macro/file) input and embedded
  84.  *        comments appropriately.  Note that the global
  85.  *        instring is -- essentially -- a parameter to get().
  86.  * cget()    Like get(), but skip over TOK_SEP.
  87.  * unget()    Push last gotten character back on the input stream.
  88.  * cerror(), cwarn(), cfatal(), cierror(), ciwarn()
  89.  *        These routines format an print messages to the user.
  90.  *        cerror & cwarn take a format and a single string argument.
  91.  *        cierror & ciwarn take a format and a single int (char) argument.
  92.  *        cfatal takes a format and a single string argument.
  93.  */
  94.  
  95. /*
  96.  
  97.  *
  98.  * Note that several "non-visible" characters have special meaning
  99.  * and are defined in cpp.h.  
  100.  * Hex 1D DEF_MAGIC -- a flag to prevent #define recursion.
  101.  * Hex 1E TOK_SEP   -- a delimiter for token concatenation
  102.  * Hex 1F COM_SEP   -- a zero-width whitespace for comment concatenation
  103.  */
  104. #if CHARSET == EBCDIC
  105. #if DEF_MAGIC != 0x19 || TOK_SEP != 0x1A || COM_SEP != 0x1B
  106.     << error type table isn't correct >>
  107. #endif
  108. #else
  109. #if DEF_MAGIC != 0x1D || TOK_SEP != 0x1E || COM_SEP != 0x1F
  110.     << error type table isn't correct >>
  111. #endif
  112. #endif
  113.  
  114. #if OK_DOLLAR
  115. #define    DOL    LET
  116. #else
  117. #define    DOL    000
  118. #endif
  119.  
  120. #if CHARSET == EBCDIC
  121.  
  122. char type[256] = {    /* Character type codes EBCDIC     Hex          */
  123.    END,   000,   000,   000,   000,   000,   000,   000, /* 00        */
  124.    000,   000,   000,   000,   000,   000,   000,   000, /* 08        */
  125.    000,   000,   000,   000,   000,   000,   000,   000, /* 10        */
  126.    000,   LET,   000,   SPA,   000,   000,   000,   000, /* 18       XXXX    */
  127.    000,   000,   000,   000,   000,   000,   000,   000, /* 20(reserved)*/
  128.    000,   000,   000,   000,   000,   000,   000,   000, /* 28(  for   )*/
  129.    000,   000,   000,   000,   000,   000,   000,   000, /* 30(MAC_PARM)*/
  130.    000,   000,   000,   000,   000,   000,   000,   000, /* 38( table  )*/
  131.    SPA,   000,   000,   000,   000,   000,   000,   000, /* 40             */
  132.    000,   000,   000,   DOT, OP_LT,OP_LPA,OP_ADD, OP_OR, /* 48    .<(+     */
  133. OP_AND,   000,   000,   000,   000,   000,   000,   000, /* 50 &           */
  134.    000,   000,OP_NOT,   DOL,OP_MUL,OP_RPA,   000,OP_XOR, /* 58   !$*);^    */
  135. OP_SUB,OP_DIV,   000,   000,   000,   000,   000,   000, /* 60 -/          */
  136.    000,   000, OP_OR,   000,OP_MOD,   LET, OP_GT,OP_QUE, /* 68   |,%_>?    */
  137.    000,   000,   000,   000,   000,   000,   000,   000, /* 70             */
  138.    000,   000,OP_COL,   000,   000,   QUO, OP_EQ,   QUO, /* 78   :#@'="    */
  139.    000,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 80  abcdefg    */
  140.    LET,   LET,   000,   000,   000,   000,   000,   000, /* 88 hi          */
  141.    000,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 90  jklmnop    */
  142.    LET,   LET,   000,   000,   000,   000,   000,   000, /* 98 qr         */
  143.    000,OP_NOT,   LET,   LET,   LET,   LET,   LET,   LET, /* A0  ~stuvwx */
  144.    LET,   LET,   000,   000,   000,   000,   000,   000, /* A8 yz   [     */
  145.    000,   000,   000,   000,   000,   000,   000,   000, /* B0            */
  146.    000,   000,   000,   000,   000,   000,   000,   000, /* B8      ]     */
  147.    000,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* C0 {ABCDEFG    */
  148.    LET,   LET,   000,   000,   000,   000,   000,   000, /* C8 HI         */
  149.    000,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* D0 }JKLMNOP    */
  150.    LET,   LET,   000,   000,   000,   000,   000,   000, /* D8 QR         */
  151.    BSH,   SPA,   LET,   LET,   LET,   LET,   LET,   LET, /* E0 \ STUVWX    */
  152.    LET,   LET,   000,   000,   000,   000,   000,   000, /* E8 YZ         */
  153.    DIG,   DIG,   DIG,   DIG,   DIG,   DIG,   DIG,   DIG, /* F0 01234567    */
  154.    DIG,   DIG,   000,   000,   000,   000,   000,   000, /* F8 89         */
  155. };
  156.  
  157. #else   
  158.  
  159. char type[256] = {    /* Character type codes ASCII      Hex          */ 
  160.    END,   000,   000,   000,   000,   000,   000,   000, /* 00        */
  161.    000,   SPA,   000,   000,   000,   000,   000,   000, /* 08        */
  162.    000,   000,   000,   000,   000,   000,   000,   000, /* 10        */
  163.    000,   000,   000,   000,   000,   LET,   000,   SPA, /* 18        */
  164.    SPA,OP_NOT,   QUO,   000,   DOL,OP_MOD,OP_AND,   QUO, /* 20  !"#$%&'    */
  165. OP_LPA,OP_RPA,OP_MUL,OP_ADD,   000,OP_SUB,   DOT,OP_DIV, /* 28 ()*+,-./    */
  166.    DIG,   DIG,   DIG,   DIG,   DIG,   DIG,   DIG,   DIG, /* 30 01234567    */
  167.    DIG,   DIG,OP_COL,   000, OP_LT, OP_EQ, OP_GT,OP_QUE, /* 38 89:;<=>?    */
  168.    000,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 40 @ABCDEFG    */
  169.    LET,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 48 HIJKLMNO    */
  170.    LET,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 50 PQRSTUVW    */
  171.    LET,   LET,   LET,   000,   BSH,   000,OP_XOR,   LET, /* 58 XYZ[\]^_    */
  172.    000,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 60 `abcdefg    */
  173.    LET,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 68 hijklmno    */
  174.    LET,   LET,   LET,   LET,   LET,   LET,   LET,   LET, /* 70 pqrstuvw    */
  175.    LET,   LET,   LET,   000, OP_OR,   000,OP_NOT,   000, /* 78 xyz{|}~    */
  176.    000,   000,   000,   000,   000,   000,   000,   000, /* 80(reserved)*/
  177.    000,   000,   000,   000,   000,   000,   000,   000, /* 88(   for  )*/
  178.    000,   000,   000,   000,   000,   000,   000,   000, /* 90(MAC_PARM)*/
  179.    000,   000,   000,   000,   000,   000,   000,   000, /* 98(  table )*/
  180.    000,   000,   000,   000,   000,   000,   000,   000, /* A0            */
  181.    000,   000,   000,   000,   000,   000,   000,   000, /* A8            */
  182.    000,   000,   000,   000,   000,   000,   000,   000, /* B0            */
  183.    000,   000,   000,   000,   000,   000,   000,   000, /* B8            */
  184.    000,   000,   000,   000,   000,   000,   000,   000, /* C0   not      */
  185.    000,   000,   000,   000,   000,   000,   000,   000, /* C8   used     */
  186.    000,   000,   000,   000,   000,   000,   000,   000, /* D0            */
  187.    000,   000,   000,   000,   000,   000,   000,   000, /* D8            */
  188.    000,   000,   000,   000,   000,   000,   000,   000, /* E0            */
  189.    000,   000,   000,   000,   000,   000,   000,   000, /* E8            */
  190.    000,   000,   000,   000,   000,   000,   000,   000, /* F0            */
  191.    000,   000,   000,   000,   000,   000,   000,   000, /* F8            */
  192. };
  193. #endif
  194.  
  195. skipnl()
  196. /*
  197.  * Skip to the end of the current input line.
  198.  */
  199. {
  200.     register int        c;
  201.  
  202.     do {                /* Skip to newline    */
  203.         c = get();
  204.     } while (c != '\n' && c != EOF_CHAR);
  205. }
  206.  
  207. int
  208. skipws()
  209. /*
  210.  * Skip over whitespace
  211.  */
  212. {
  213.     register int        c;
  214.  
  215.     do {                /* Skip whitespace    */
  216.         c = get();
  217. #if COMMENT_INVISIBLE
  218.     } while (type[c] == SPA || c == COM_SEP);
  219. #else
  220.     } while (type[c] == SPA);
  221. #endif
  222.     return (c);
  223. }
  224.  
  225. scanid(c)
  226. register int    c;                /* First char of id    */
  227. /*
  228.  * Get the next token (an id) into the token buffer.
  229.  * Note: this code is duplicated in lookid().
  230.  * Change one, change both.
  231.  */
  232. {
  233.     register int ct;
  234.  
  235.     if (c == DEF_MAGIC)            /* Eat the magic token    */
  236.         c = get();                /* undefiner.        */
  237.     ct = 0;
  238.     do
  239.       {
  240.         if (ct == tokenbsize)
  241.           tokenbuf = incmem (tokenbuf, 1 + (tokenbsize *= 2));
  242.         tokenbuf[ct++] = c;
  243.         c = get();
  244.       }
  245.     while (type[c] == LET || type[c] == DIG);
  246.     unget();
  247.     tokenbuf[ct] = EOS;
  248. }
  249.  
  250. /* macro_name and make_Infile used by macroid()
  251.  * for macro recursion
  252.  */
  253.  
  254. static struct macro_name {char *name; struct macro_name *next;} *Infile;
  255.  
  256. make_Infile(file)
  257. FILEINFO *file;
  258. {
  259.  struct macro_name *ifile;
  260.  extern char *malloc();
  261.  char *str;
  262.  
  263.  ifile = (struct macro_name *) malloc(sizeof(struct macro_name));
  264.  str = (char *)malloc(sizeof(file->filename + 1));
  265.  ifile->name = strcpy(str,file->filename);
  266.  if (Infile == NULL) {
  267.    Infile = ifile;
  268.    ifile->next = NULL;
  269.  }
  270. /* if (Infile == NULL) Infile = ifile; */
  271.  else {
  272.     ifile->next = Infile;
  273.     Infile = ifile;
  274.   }
  275. }
  276.  
  277. int
  278. macroid(c)
  279. register int        c;
  280. /*
  281.  * If c is a letter, scan the id.  if it's #defined, expand it and scan
  282.  * the next character and try again.
  283.  *
  284.  * Else, return the character.  If type[c] is a LET, the token is in tokenbuf.
  285.  */
  286. {
  287.     register DEFBUF    *dp;
  288.  
  289.     if (infile != NULL && infile->fp != NULL)
  290.         recursion = 0;
  291.     while (type[c] == LET && (dp = lookid(c)) != NULL) {
  292.         expand(dp);
  293.         c = get();
  294.     }
  295.     return (c);
  296. }
  297.  
  298. /*****recursive fix here breaks use of defmacro class, 
  299.       so temporarily taking it out
  300. int
  301. macroid(c)
  302. register int        c;
  303.  *
  304.  * If c is a letter, scan the id.  if it's #defined, expand it and scan
  305.  * the next character and try again.
  306.  *
  307.  * Else, return the character.  If type[c] is a LET, the token is in tokenbuf.
  308.  *
  309. {
  310.     register DEFBUF    *dp;
  311.         struct macro_name *ifile;
  312.         FILEINFO *ifile1;
  313.         int flag = 0;
  314.  
  315.     if (infile != NULL && infile->fp != NULL) {
  316.         recursion = 0;
  317.             Infile = NULL;
  318.       }
  319.     else make_Infile(infile);
  320.  
  321.     while (type[c] == LET && (dp = lookid(c)) != NULL) {
  322.             if (Infile != NULL) {
  323.                ifile = Infile;
  324.                while (ifile != NULL) {
  325.                      if (strcmp(dp->name,ifile->name) == 0) {
  326.                         cwarn("macro recursion in %s",dp->name);
  327.             return(c);
  328.              }
  329.                      ifile = ifile->next;
  330.            }
  331.          }
  332.             ifile1 = infile;
  333.         expand(dp);
  334.             if (ifile1 != infile) make_Infile(infile);
  335.         c = get();
  336.       }
  337.     return (c);
  338. }
  339. *****end of recursive macro fix */
  340.  
  341.  
  342. int
  343. scanstring(delim, outfun)
  344. register int    delim;            /* ' or "            */
  345. int        (*outfun)();        /* Output function        */
  346. /*
  347.  * Scan off a string.  Warning if terminated by newline or EOF.
  348.  * outfun() outputs the character -- to a buffer if in a macro.
  349.  * TRUE if ok, FALSE if error.
  350.  */
  351. {
  352.     register int        c;
  353.  
  354.     instring = TRUE;        /* Don't strip comments        */
  355.     (*outfun)(delim);
  356.     while ((c = get()) != delim
  357.          && c != '\n'
  358.          && c != EOF_CHAR) {
  359.       if (c == '\\') {
  360.         c = get();
  361.         if (c == '\n') ;        /* Don't output backslash newline */
  362.         else {
  363.           (*outfun)('\\');
  364.           (*outfun)(c);
  365.         }
  366.       }
  367.       else (*outfun)(c);
  368.     }
  369.     instring = FALSE;
  370.     if (c == delim) {
  371.         (*outfun)(c);
  372.         return (TRUE);
  373.     }
  374.     else {
  375.         cerror("Unterminated string", NULLST);
  376.         unget();
  377.         return (FALSE);
  378.     }
  379. }
  380.  
  381. scannumber(c, outfun)
  382. register int    c;                /* First char of number    */
  383. register int    (*outfun)();            /* Output/store func    */
  384. /*
  385.  * Process a number.  We know that c is from 0 to 9 or dot.
  386.  * Algorithm from Dave Conroy's Decus C.
  387.  */
  388. {
  389.     register int    radix;            /* 8, 10, or 16        */
  390.     int        expseen;        /* 'e' seen in floater    */
  391.     int        signseen;        /* '+' or '-' seen    */
  392.     int        octal89;        /* For bad octal test    */
  393.     int        dotflag;        /* TRUE if '.' was seen    */
  394.  
  395.     expseen = FALSE;            /* No exponent seen yet    */
  396.     signseen = TRUE;            /* No +/- allowed yet    */
  397.     octal89 = FALSE;            /* No bad octal yet    */
  398.     radix = 10;                /* Assume decimal    */
  399.     if ((dotflag = (c == '.')) != FALSE) {    /* . something?        */
  400.         (*outfun)('.');            /* Always out the dot    */
  401.         if (type[(c = get())] != DIG) {    /* If not a float numb,    */
  402.         unget();            /* Rescan strange char    */
  403.         return;                /* All done for now    */
  404.         }
  405.     }                    /* End of float test    */
  406.     else if (c == '0') {            /* Octal or hex?    */
  407.         (*outfun)(c);            /* Stuff initial zero    */
  408.         radix = 8;                /* Assume it's octal    */
  409.         c = get();                /* Look for an 'x'    */
  410.         if (c == 'x' || c == 'X') {        /* Did we get one?    */
  411.         radix = 16;            /* Remember new radix    */
  412.         (*outfun)(c);            /* Stuff the 'x'    */
  413.         c = get();            /* Get next character    */
  414.         }
  415.     }
  416.     for (;;) {                /* Process curr. char.    */
  417.         /*
  418.          * Note that this algorithm accepts "012e4" and "03.4"
  419.          * as legitimate floating-point numbers.
  420.          */
  421.         if (radix != 16 && (c == 'e' || c == 'E')) {
  422.         if (expseen)            /* Already saw 'E'?    */
  423.             break;            /* Exit loop, bad nbr.    */
  424.         expseen = TRUE;            /* Set exponent seen    */
  425.         signseen = FALSE;        /* We can read '+' now    */
  426.         radix = 10;            /* Decimal exponent    */
  427.         }
  428.         else if (radix != 16 && c == '.') {
  429.         if (dotflag)            /* Saw dot already?    */
  430.             break;            /* Exit loop, two dots    */
  431.         dotflag = TRUE;            /* Remember the dot    */
  432.         radix = 10;            /* Decimal fraction    */
  433.         }
  434.         else if (c == '+' || c == '-') {    /* 1.0e+10        */
  435.         if (signseen)            /* Sign in wrong place?    */
  436.             break;            /* Exit loop, not nbr.    */
  437.         /* signseen = TRUE; */        /* Remember we saw it    */
  438.         }
  439.         else {                /* Check the digit    */
  440.         switch (c) {
  441.         case '8': case '9':        /* Sometimes wrong    */
  442.             octal89 = TRUE;        /* Do check later    */
  443.         case '0': case '1': case '2': case '3':
  444.         case '4': case '5': case '6': case '7':
  445.             break;            /* Always ok        */
  446.  
  447.         case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
  448.         case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
  449.             if (radix == 16)        /* Alpha's are ok only     */
  450.             break;            /* if reading hex.    */
  451.         default:            /* At number end    */
  452.             goto done;            /* Break from for loop    */
  453.         }                /* End of switch    */
  454.         }                    /* End general case    */
  455.         (*outfun)(c);            /* Accept the character    */
  456.         signseen = TRUE;            /* Don't read sign now    */
  457.         c = get();                /* Read another char    */
  458.     }                    /* End of scan loop    */
  459.     /*
  460.      * When we break out of the scan loop, c contains the first
  461.      * character (maybe) not in the number.  If the number is an
  462.      * integer, allow a trailing 'L' for long and/or a trailing 'U'
  463.      * for unsigned.  If not those, push the trailing character back
  464.      * on the input stream.  Floating point numbers accept a trailing
  465.      * 'L' for "long double".
  466.      */
  467. done:    if (dotflag || expseen) {        /* Floating point?    */
  468.         if (c == 'l' || c == 'L') {
  469.         (*outfun)(c);
  470.         c = get();            /* Ungotten later    */
  471.         }
  472.     }
  473.     else {                    /* Else it's an integer    */
  474.         /*
  475.           * We know that dotflag and expseen are both zero, now:
  476.          * dotflag signals "saw 'L'", and
  477.          * expseen signals "saw 'U'".
  478.          */
  479.         for (;;) {
  480.         switch (c) {
  481.         case 'l':
  482.         case 'L':
  483.             if (dotflag)
  484.             goto nomore;
  485.             dotflag = TRUE;
  486.             break;
  487.  
  488.         case 'u':
  489.         case 'U':
  490.             if (expseen)
  491.             goto nomore;
  492.             expseen = TRUE;
  493.             break;
  494.  
  495.         default:
  496.             goto nomore;
  497.         }
  498.         (*outfun)(c);            /* Got 'L' or 'U'.    */
  499.         c = get();            /* Look at next, too.    */
  500.         }
  501.     }
  502. nomore:    unget();                /* Not part of a number    */
  503.     if (octal89 && radix == 8)
  504.         cwarn("Illegal digit in octal number", NULLST);
  505. }
  506.  
  507. save(c)
  508. register int    c;
  509. {
  510.     if (workp >= &work[NWORK]) {
  511.       work[NWORK-1] = EOS;
  512.       cfatal("Work buffer overflow", NULLST);
  513.     }
  514.     else *workp++ = (char) c;
  515. }
  516.  
  517. char *
  518. savestring(text)
  519. char        *text;
  520. /*
  521.  * Store a string into free memory.
  522.  */
  523. {
  524.     register char    *result;
  525.  
  526.     result = getmem(strlen(text) + 1);
  527.     strcpy(result, text);
  528.     return (result);
  529. }
  530.  
  531. FILEINFO    *
  532. getfile(bufsize, name)
  533. int        bufsize;        /* Line or define buffer size    */
  534. char        *name;            /* File or macro name string    */
  535. /*
  536.  * Common FILEINFO buffer initialization for a new file or macro.
  537.  */
  538. {
  539.     register FILEINFO    *file;
  540.  
  541.     file = (FILEINFO *) getmem(sizeof (FILEINFO));
  542.     file->buffer = getmem(bufsize + 1);
  543.     file->bptr = file->buffer;        /* Initialize line ptr    */
  544.     file->buffer[0] = EOS;            /* Force first read    */
  545.     file->parent = infile;            /* Chain files together    */
  546.     file->fp = NULL;            /* No file yet        */
  547.     file->filename = savestring(name);    /* Save file/macro name    */
  548.     file->progname = NULL;            /* No #line seen yet    */
  549.     file->unrecur = 0;            /* No macro fixup    */
  550.     file->line = 0;                /* (Not used just yet)    */
  551.     if (infile != NULL)            /* If #include file    */
  552.         infile->line = line;        /* Save current line    */
  553.     infile = file;                /* New current file    */
  554.     line = 1;                /* Note first line    */
  555.     return (file);                /* All done.        */
  556. }
  557.  
  558. char *
  559. getmem(size)
  560. int        size;
  561. /*
  562.  * Get a block of free memory.
  563.  */
  564. {
  565.     register char    *result;
  566.     extern char    *malloc();
  567.  
  568.     if ((result = malloc((unsigned) size)) == NULL)
  569.         cfatal("Out of memory", NULLST);
  570.     return (result);
  571. }
  572.  
  573. char *
  574. incmem(obj,size)
  575. char        *obj;
  576. int        size;
  577. /*
  578.  * Get a block of free memory.
  579.  */
  580. {
  581.     register char    *result;
  582.     extern char    *realloc();
  583.  
  584.     if ((result = realloc(obj, (unsigned) size)) == NULL)
  585.         cfatal("Out of memory", NULLST);
  586.     return (result);
  587. }
  588.  
  589. /*
  590.  *            C P P   S y m b o l   T a b l e s
  591.  */
  592.  
  593. /*
  594.  * SBSIZE defines the number of hash-table slots for the symbol table.
  595.  * It must be a power of 2.
  596.  */
  597. #ifndef    SBSIZE
  598. #define    SBSIZE    64
  599. #endif
  600. #define    SBMASK    (SBSIZE - 1)
  601. #if (SBSIZE ^ SBMASK) != ((SBSIZE * 2) - 1)
  602.     << error, SBSIZE must be a power of 2 >>
  603. #endif
  604.  
  605. static DEFBUF    *symtab[SBSIZE];    /* Symbol table queue headers    */
  606.  
  607. DEFBUF *
  608. lookid(c)
  609. int    c;                /* First character of token    */
  610. /*
  611.  * Look for the next token in the symbol table.  Returns token in tokenbuf.
  612.  * If found, returns the table pointer;  Else returns NULL.
  613.  */
  614. {
  615.     register int        nhash;
  616.     register DEFBUF        *dp;
  617.     register int        ct;
  618.     int            temp = 0;
  619.     int            isrecurse;    /* For #define foo foo    */
  620.  
  621.     nhash = 0;
  622.     if ((isrecurse = (c == DEF_MAGIC)))    /* If recursive macro    */
  623.         c = get();                /* hack, skip DEF_MAGIC    */
  624.     ct = 0;
  625.     do
  626.       {
  627.         if (ct == tokenbsize)
  628.           tokenbuf = incmem(tokenbuf, 1 + (tokenbsize *= 2));
  629.         tokenbuf[ct++] = c;        /* Store token byte    */
  630.         nhash += c;            /* Update hash value    */
  631.         c = get();
  632.       }
  633.     while (type[c] == LET || type[c] == DIG);
  634.     unget();                /* Rescan terminator    */
  635.     tokenbuf[ct] = EOS;            /* Terminate token    */
  636.     if (isrecurse)                /* Recursive definition    */
  637.         return (NULL);            /* undefined just now    */
  638.     nhash += ct;                /* Fix hash value    */
  639.     dp = symtab[nhash & SBMASK];        /* Starting bucket    */
  640.     while (dp != (DEFBUF *) NULL) {        /* Search symbol table    */
  641.         if (dp->hash == nhash        /* Fast precheck    */
  642.          && (temp = strcmp(dp->name, tokenbuf)) >= 0)
  643.         break;
  644.         dp = dp->link;            /* Nope, try next one    */
  645.     }
  646.     return ((temp == 0) ? dp : NULL);
  647. }
  648.  
  649. DEFBUF *
  650. defendel(name, delete)
  651. char        *name;
  652. int        delete;            /* TRUE to delete a symbol    */
  653. /*
  654.  * Enter this name in the lookup table (delete = FALSE)
  655.  * or delete this name (delete = TRUE).
  656.  * Returns a pointer to the define block (delete = FALSE)
  657.  * Returns NULL if the symbol wasn't defined (delete = TRUE).
  658.  */
  659. {
  660.     register DEFBUF        *dp;
  661.     register DEFBUF        **prevp;
  662.     register char        *np;
  663.     int            nhash;
  664.     int            temp;
  665.     int            size;
  666.  
  667.     for (nhash = 0, np = name; *np != EOS;)
  668.         nhash += *np++;
  669.     size = (np - name);
  670.     nhash += size;
  671.     prevp = &symtab[nhash & SBMASK];
  672.     while ((dp = *prevp) != (DEFBUF *) NULL) {
  673.         if (dp->hash == nhash
  674.          && (temp = strcmp(dp->name, name)) >= 0) {
  675.         if (temp > 0)
  676.             dp = NULL;            /* Not found        */
  677.         else {
  678.             *prevp = dp->link;        /* Found, unlink and    */
  679.             if (dp->repl != NULL)    /* Free the replacement    */
  680.             free(dp->repl);        /* if any, and then    */
  681.             free((char *) dp);        /* Free the symbol    */
  682.             dp = NULL;                /* Zap pointer */
  683.         }
  684.         break;
  685.         }
  686.         prevp = &dp->link;
  687.     }
  688.     if (!delete) {
  689.         dp = (DEFBUF *) getmem(sizeof (DEFBUF) + size);
  690.         dp->link = *prevp;
  691.         *prevp = dp;
  692.         dp->hash = nhash;
  693.         dp->repl = NULL;
  694.         dp->nargs = 0;
  695.         strcpy(dp->name, name);
  696.     }
  697.     return (dp);
  698. }
  699.  
  700. #if DEBUG
  701.  
  702. dumpdef(why)
  703. char        *why;
  704. {
  705.     register DEFBUF        *dp;
  706.     register DEFBUF        **syp;
  707.  
  708.     printf("CPP symbol table dump %s\n", why);
  709.     for (syp = symtab; syp < &symtab[SBSIZE]; syp++) {
  710.         if ((dp = *syp) != (DEFBUF *) NULL) {
  711.         printf("symtab[%d]\n", (syp - symtab));
  712.         do {
  713.             dumpadef((char *) NULL, dp);
  714.         } while ((dp = dp->link) != (DEFBUF *) NULL);
  715.         }
  716.     }
  717. }
  718.  
  719. dumpadef(why, dp)
  720. char        *why;            /* Notation            */
  721. register DEFBUF    *dp;
  722. {
  723.     register char        *cp;
  724.     register int        c;
  725.  
  726.     printf(" \"%s\" [%d]", dp->name, dp->nargs);
  727.     if (why != NULL)
  728.         printf(" (%s)", why);
  729.     if (dp->repl != NULL) {
  730.         printf(" => ");
  731.         for (cp = dp->repl; (c = *cp++ & 0xFF) != EOS;) {
  732.         if (c >= MAC_PARM && c <= (MAC_PARM + PAR_MAC))
  733.             printf("<%d>", c - MAC_PARM);
  734.         else if (isprint(c) || c == '\n' || c == '\t')
  735.             putchar(c);
  736.         else if (c < ' ')
  737.             printf("<^%c>", c + '@');
  738.         else
  739.             printf("<\\0%o>", c);
  740.         }
  741.     }
  742.     else {
  743.         printf(", no replacement.");
  744.     }
  745.     putchar('\n');
  746. }
  747. #endif
  748.  
  749. /*
  750.  * PEEK
  751.  *     Return the next chartacter to be returned from get,
  752.  *     but don't actually remove it from the input buffer.
  753.  *
  754.  * This is used while doing comment lookahead in get.
  755.  * Try to avoid doing get/unget, because it gives us trouble
  756.  * when at the end of a buffer (the caller of get sometimes needs
  757.  * to do an unget, and two ungets in a row is unreliable)
  758.  */
  759. int peek() {
  760.   register int        c;
  761.  
  762.   if (infile == NULL)
  763.     return (EOF_CHAR);
  764.   if ((c = *infile->bptr) == EOS) {
  765.     if (infile->fp == NULL)       /* NULL if macro    */
  766.       c = *(infile->parent->bptr);
  767.     else {
  768.       instring = TRUE;
  769.       c = get();
  770.       instring = FALSE;
  771.       unget();
  772.     }
  773.   }
  774.   return c;
  775. }
  776.     
  777. /*
  778.  *            G E T
  779.  */
  780.  
  781. int
  782. get()
  783. /*
  784.  * Return the next character from a macro or the current file.
  785.  * Handle end of file from #include files.
  786.  */
  787. {
  788.     register int        c;
  789.  
  790. get_from_file:
  791.     if (infile == NULL)
  792.         return (EOF_CHAR);
  793. newline:
  794. #if DEBUG
  795.     printf("get(%s), recursion %d, line %d, bptr = %d, buffer \"%s\"\n",
  796.         infile->filename, recursion, line,
  797.         infile->bptr - infile->buffer, infile->buffer);
  798. #endif
  799.     /*
  800.      * Read a character from the current input line or macro.
  801.      * At EOS, either finish the current macro (freeing temp.
  802.      * storage) or read another line from the current input file.
  803.      * At EOF, exit the current file (#include) or, at EOF from
  804.      * the cpp input file, return EOF_CHAR to finish processing.
  805.      */
  806.     switch (c = *infile->bptr++) {
  807.       case EOS: {
  808.         register FILEINFO    *file = infile;
  809.         /*
  810.          * Nothing in current line or macro.  Get next line (if
  811.          * input from a file), or do end of file/macro processing.
  812.          * In the latter case, jump back to restart from the top.
  813.          */
  814.         if (file->fp == NULL) {      /* NULL if macro    */
  815.           recursion--;
  816.           if (recursion < 0)
  817.         recursion = 0;
  818.           infile = file->parent;      /* Unwind file chain    */
  819.         }
  820.         else {              /* Else get from a file    */
  821.           if ((file->bptr = fgets(file->buffer, NBUFF, file->fp))
  822.           != NULL) {
  823. #if DEBUG
  824.         if (debug > 1) {      /* Dump it to stdout    */
  825.           printf("\n#line %d (%s), %s",
  826.              line, file->filename, file->buffer);
  827.         }
  828. #endif
  829.         goto newline;          /* process the line    */
  830.           }
  831.           else {
  832.         fclose(file->fp);      /* Close finished file    */
  833.         if ((infile = file->parent) != NULL) {
  834.           /*
  835.            * There is an "ungotten" newline in the current
  836.            * infile buffer (set there by doinclude() in
  837.            * cpp1.c).  Thus, we know that the mainline code
  838.            * is skipping over blank lines and will do a
  839.            * #line at its convenience.
  840.            */
  841.           wrongline = TRUE;      /* Need a #line now    */
  842.         }
  843.           }
  844.         }
  845.  
  846.         /*
  847.          * Free up space used by the (finished) file or macro and
  848.          * restart input from the parent file/macro, if any.
  849.          */
  850.         free(file->filename);      /* Free name and    */
  851.         if (file->progname != NULL)      /* if a #line was seen,    */
  852.           free(file->progname);      /* free it, too.    */
  853.         free(file->buffer);          /* Free buffer */
  854.         free((char *) file);      /* Free file space    */
  855.         if (infile == NULL)          /* If at end of file    */
  856.           return (EOF_CHAR);      /* Return end of file    */
  857.         line = infile->line;      /* Reset line number    */
  858.         goto get_from_file;          /* Get from the top.    */
  859.       }
  860.       /* break; // this statement never reached */
  861.  
  862.         /*
  863.          * Common processing for the new character.
  864.          */
  865.       case DEF_MAGIC:
  866.         if (infile->fp != NULL)      /* Don't allow delete    */
  867.         goto newline;          /* from a file    */
  868.         break;
  869.       case '\n':              /* Maintain current    */
  870.         ++line;              /* line counter    */
  871.         break;
  872.       case '/':              /* Comment?        */
  873.         if (instring) return (c);      /* Strings just return the char */
  874.         if ((c = peek()) != '*' &&      /* Next byte '*'?    */
  875.         c != '/') {          /* or '/'?            */
  876.           instring = FALSE;          /* Nope, no comment    */
  877.           return ('/');          /* Return the slash    */
  878.         }
  879.         instring = TRUE;          /* So get() won't loop*/
  880.         if((c = get()) == '/') {      /* C++ comment        */
  881.           if (keepcomments) {      /* If writing comments*/
  882.         putchar('/');          /* Write out the    */
  883.         putchar(c);          /*   initializer    */
  884.         while ((c = get()) != '\n' && c != EOF_CHAR)
  885.           putchar(c);
  886.           } else {              /* Eat a comment    */
  887.         while ((c = get()) != '\n' && c != EOF_CHAR);
  888.           }
  889.           instring = FALSE;          /* End of c++ comment    */
  890.           return(c);
  891.         } else {              /* Normal comment     */
  892.           if (keepcomments) {      /* If writing comments*/
  893.         putchar('/');          /* Write out the    */
  894.         putchar(c);          /*   initializer    */
  895.           }
  896.           for (;;) {          /* Eat a comment    */
  897.         c = get();
  898.           test:
  899.         if (c == EOF_CHAR) {
  900.           cerror("EOF in comment", NULLST);
  901.           return (EOF_CHAR);
  902.         }
  903.         if (keepcomments)
  904.           cput(c);
  905.         switch (c) {
  906. #ifdef NOTDEF
  907.         case '/':
  908.           if ((c = get()) != '*') /* Don't let comments    */
  909.             goto test;          /* Nest.        */
  910.           cwarn("Nested comments", NULLST);
  911. #endif                      /* NOTDEF */
  912.           /* Fall into * stuff    */
  913.         case '*':
  914.           if ((c = get()) != '/') /* If comment doesn't    */
  915.             goto test;          /* end, look at next    */
  916.           instring = FALSE;      /* End of comment,    */
  917.           if (keepcomments) {      /* Put out the comment*/
  918.             cput(c);          /* terminator, too    */
  919.           }
  920.           /*
  921.            * A comment is syntactically "whitespace" --
  922.            * however, there are certain strange sequences
  923.            * such as
  924.            *        #define foo(x)    (something)
  925.            *            foo|* comment *|(123)
  926.            *       these are '/' ^           ^
  927.            * where just returning space (or COM_SEP) will cause
  928.            * problems.  This can be "fixed" by overwriting the
  929.            * '/' in the input line buffer with ' ' (or COM_SEP)
  930.            * but that may mess up an error message.
  931.            * So, we peek ahead -- if the next character is
  932.            * "whitespace" we just get another character, if not,
  933.            * we modify the buffer.  All in the name of purity.
  934.            */
  935.           if (*infile->bptr == '\n'
  936.               || type[*infile->bptr & 0xFF] == SPA)
  937.             goto newline;
  938. #if COMMENT_INVISIBLE
  939.           /*
  940.            * Return magic (old-fashioned) syntactic space.
  941.            */
  942.           return ((infile->bptr[-1] = COM_SEP));
  943. #else
  944.           return ((infile->bptr[-1] = ' '));
  945. #endif
  946.  
  947.         case '\n':            
  948.           if (!keepcomments)      /* we'll need a #line    */
  949.             wrongline = TRUE;      /* later...        */
  950.         default:          /* Anything else is    */
  951.           break;          /* Just a character    */
  952.         }              /* End switch        */
  953.           }                  /* End comment loop    */
  954.         }                  /* End if in comment    */
  955.         /* break; // this statement never reached */
  956.         case '\\':
  957.           if (instring) return (c);      /* Strings just return the char */
  958.           if (!inmacro) {          /* If backslash, peek     */
  959.         if ((c = get()) == '\n') { /* for a <nl>.  If so,    */
  960.           wrongline = TRUE;
  961. #ifdef readable_defines
  962.           if(infile->fp == NULL && /* If Expanding a macro,*/
  963.              keepcomments)      /* And human readable   */
  964.             return(c);          /* Convert \newline to just newline */
  965.           else
  966. #endif
  967.             goto newline;
  968.         }
  969.         else {              /* Backslash anything    */
  970.           unget();          /* Get it later        */
  971.           return ('\\');      /* Return the backslash    */
  972.         }
  973.           }
  974.           break;
  975.         case '\f':
  976.         case VT:              /* Form Feed, Vertical    */
  977.           if (instring) return (c);      /* Strings just return the char */
  978.           c = ' ';              /* Tab are whitespace    */
  979.           break;
  980.         }                  /* end switch */
  981.     return (c);             /* Just return the char    */
  982. }
  983.  
  984. unget()
  985. /*
  986.  * Backup the pointer to reread the last character.  Fatal error
  987.  * (code bug) if we backup too far.  unget() may be called,
  988.  * without problems, at end of file.  Only one character may
  989.  * be ungotten.  If you need to unget more, call ungetstring().
  990.  */
  991. {
  992.     register FILEINFO    *file;
  993.  
  994.     if ((file = infile) == NULL)
  995.         return;            /* Unget after EOF        */
  996.     if (--file->bptr < file->buffer)
  997.         cfatal("Too much pushback", NULLST);
  998.     if (*file->bptr == '\n')    /* Ungetting a newline?        */
  999.         --line;            /* Unget the line number, too    */
  1000. }
  1001.  
  1002. ungetstring(text)
  1003. char        *text;
  1004. /*
  1005.  * Push a string back on the input stream.  This is done by treating
  1006.  * the text as if it were a macro.
  1007.  */
  1008. {
  1009.     register FILEINFO    *file;
  1010.     extern FILEINFO        *getfile();
  1011.  
  1012.     file = getfile(strlen(text) + 1, "");
  1013.     strcpy(file->buffer, text);
  1014. }
  1015.  
  1016. int
  1017. cget()
  1018. /*
  1019.  * Get one character, absorb "funny space" after comments or
  1020.  * token concatenation
  1021.  */
  1022. {
  1023.     register int    c;
  1024.  
  1025.     do {
  1026.         c = get();
  1027. #if COMMENT_INVISIBLE
  1028.     } while (c == TOK_SEP || c == COM_SEP);
  1029. #else
  1030.     } while (c == TOK_SEP);
  1031. #endif
  1032.     return (c);
  1033. }
  1034.  
  1035. /*
  1036.  * Error messages and other hacks.  The first byte of severity
  1037.  * is 'S' for string arguments and 'I' for int arguments.  This
  1038.  * is needed for portability with machines that have int's that
  1039.  * are shorter than  char *'s.
  1040.  */
  1041.  
  1042. static
  1043. domsg(severity, format, arg)
  1044. char        *severity;        /* "Error", "Warning", "Fatal"    */
  1045. char        *format;        /* Format for the error message    */
  1046. char        *arg;            /* Something for the message    */
  1047. /*
  1048.  * Print filenames, macro names, and line numbers for error messages.
  1049.  */
  1050. {
  1051.     register char        *tp;
  1052.     register FILEINFO    *file;
  1053.     int line_number = line;
  1054.                       /* Skip macros, get real line# */
  1055.     for (file = infile; file && !file->fp;) {
  1056.       file = file->parent;
  1057.       line_number = file->line + line - 1;
  1058.     }
  1059.     tp = file ? file->filename : 0;
  1060.     fprintf (stderr, "%s\"%s\", line %d: %s: ",
  1061.          MSG_PREFIX, tp, line_number, &severity[1]);
  1062.     if (*severity == 'S')
  1063.       fprintf(stderr, format, arg);
  1064.     else
  1065.       fprintf(stderr, format, (int) arg);
  1066.     putc('\n', stderr);
  1067.  
  1068.     while (file && (file = file->parent) != NULL) {
  1069.         /* Print #includes, too */
  1070.         tp = file->parent ? "," : ".";
  1071.         if (file->fp == NULL)
  1072.         fprintf(stderr, " from macro %s%s\n", file->filename, tp);
  1073.         else {
  1074.         fprintf(stderr, " from file %s, line %d%s\n",
  1075.             (file->progname != NULL)
  1076.             ? file->progname : file->filename,
  1077.             file->line, tp);
  1078.         }
  1079.     }
  1080. }
  1081.  
  1082. cerror(format, sarg)
  1083. char        *format;
  1084. char        *sarg;        /* Single string argument        */
  1085. /*
  1086.  * Print a normal error message, string argument.
  1087.  */
  1088. {
  1089.     domsg("SError", format, sarg);
  1090.     errors++;
  1091. }
  1092.  
  1093. cierror(format, narg)
  1094. char        *format;
  1095. int        narg;        /* Single numeric argument        */
  1096. /*
  1097.  * Print a normal error message, numeric argument.
  1098.  */
  1099. {
  1100.         long     chrptr;
  1101.  
  1102.         chrptr = (long) narg;
  1103.     domsg("IError", format, (char *) chrptr);
  1104.     errors++;
  1105. }
  1106.  
  1107. cfatal(format, sarg)
  1108. char        *format;
  1109. char        *sarg;            /* Single string argument    */
  1110. /*
  1111.  * A real disaster
  1112.  */
  1113. {
  1114.     domsg("SFatal error", format, sarg);
  1115.     exit(IO_ERROR);
  1116. }
  1117.  
  1118. cwarn(format, sarg)
  1119. char        *format;
  1120. char        *sarg;            /* Single string argument    */
  1121. /*
  1122.  * A non-fatal error, string argument.
  1123.  */
  1124. {
  1125.     domsg("SWarning", format, sarg);
  1126. }
  1127.  
  1128. ciwarn(format, narg)
  1129. char        *format;
  1130. int        narg;            /* Single numeric argument    */
  1131. /*
  1132.  * A non-fatal error, numeric argument.
  1133.  */
  1134. {
  1135.         long     chrptr;
  1136.  
  1137.         chrptr = (long) narg;
  1138.     domsg("IWarning", format, (char *) chrptr);
  1139. }
  1140.  
  1141.  
  1142.